package com.shibaobei.activity.service;

import com.shibaobei.activity.dao.ApproveInfoMapper;
import com.shibaobei.activity.model.Application;
import com.shibaobei.activity.model.ApproveInfo;
import com.shibaobei.activity.model.User;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2020/5/10 0010.
 */
@Service
public class ApproveInfoService {
    @Autowired
    private ApproveInfoMapper approveInfoMapper;
    @Autowired
    private ApplicationService applicationService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;

    public List<ApproveInfo> findListByApplicationId(String applicationId) {
        return approveInfoMapper.findListByApplicationId(applicationId);
    }

    public void approve(Integer applicationId, String taskId, Boolean approval, String comment, User user) {
        Application application = applicationService.findById(applicationId);
        //查询流程实例id
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        String processInstanceId = task.getProcessInstanceId();

        //1、包装一个审批实体并保存
        ApproveInfo approveInfo = new ApproveInfo();
        approveInfo.setApplication(application);
        approveInfo.setApproval(approval);
        approveInfo.setComment(comment);
        approveInfo.setApproveDate(new Date());
        approveInfo.setApprover(user);
        approveInfoMapper.insert(approveInfo);
        //2、办理当前的任务
        taskService.complete(taskId);
        //查询当前流程实例是否存在
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        if(approveInfo.isApproval()){ //3、如果审批的结果为‘通过’
            if(null == processInstance){ //如果当前办理人为最后一个节点，将申请的状态修改为‘已通过’
                application.setStatus(Application.STATUS_APPROVED);
                applicationService.update(application);
            }
        }else{ //4、如果审批的结果为‘不通过’
            // 将申请的状态修改为‘不通过’，
            application.setStatus(Application.STATUS_UNAPPROVED);
            applicationService.update(application);
            // 如果当前办理人不是最后一个节点，手动结束流程
            if(null != processInstance){
                runtimeService.deleteProcessInstance(processInstanceId,Application.STATUS_UNAPPROVED);
            }
        }
    }
}
